{% extends 'layout/manage.html' %}
{% load dashboard %}
{% load issues %}
{% block title %}{% endblock %}

{% block css %}
    <style>

        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 17px;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked + .slider {
            background-color: #2196F3;
        }

        input:focus + .slider {
            box-shadow: 0 0 1px #2196F3;
        }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* Rounded sliders */
        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }

        .table-right > tbody > tr > td.label-left {
            width: 90px;
        }

        .table-right > tbody > tr > td {
            border: 0;
        }

        .status-count {
            text-align: center;
            margin-top: 10px;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .status-count .count {
            font-size: 25px;
        }

        .status-count a {
            text-decoration: none;
        }

        .user-item .title {
            margin-bottom: 20px;
        }

        .user-item .avatar, .top-10 .avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .user-item .text {
            line-height: 30px;
        }

        .top-10 .avatar {
            margin-right: 0;
        }

        .top-10 td {
            padding: 5px 10px;
        }

        .top-10 .table > tbody > tr > td {
            border-top: 0;
            border-bottom: 1px solid #ddd;
        }
    </style>

{% endblock %}


{% block content %}

    <div class="container-fluid" style="margin-top: 20px">
        <div id="body-content">
            <div class="layui-col-md8">
                <div id="chart" style="width:115%;min-width:700px;min-height:400px">
                </div>
            </div>
        </div>
        <div class="layui-col-md4" style="padding-top: 3%">
            <div class="" style="width: 120px;float:right;padding-right: 2%">年份选择</div>
            <div class="layui-inline" style="float:right;padding-right: 4%">
                <input type="text" class="layui-input" id="ID-laydate-type-year" placeholder="yyyy">
            </div>
        </div>
    </div>

    <input id="csrf_token" value="{{ csrf_token }}" hidden="hidden"/>

{% endblock %}

{% block js %}
    <script type="text/javascript">
        var myChart = echarts.init(document.getElementById("chart"));
        var dayListDirect = '[]'
        {#var dayList = (localStorage.getItem("dayList" +{{ request.web.project.id}})) || dayListDirect#}
        var dayList = dayListDirect

        var yearSelect = localStorage.getItem("yearSelect") ? localStorage.getItem("yearSelect") : new Date().getFullYear();

        function getCalendarList(year) {
            console.log('get calendar list')
            $.ajax({
                url: "{% url 'work_record_list' project_id=request.web.project.id %}",
                type: "GET",
                async: false,
                data: {
                    "year": year == null ? yearSelect : year,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                {#dataType: "JSON",#}
                success: function (res) {
                    console.log(res);
                    if (res.status) {
                        {#console.log("reload")#}
                        {#location.reload();#}
                        {#console.log('res data : ', JSON.stringify((res.data)))#}
                        {#console.log('res data : ', JSON.stringify(res.data))#}
                        {#localStorage.setItem("dayList" +{{ request.web.project.id}}, JSON.stringify(res.data))#}
                        dayListDirect = JSON.stringify(res.data)
                    } else {
                        localStorage.setItem("dayList" +{{ request.web.project.id}}, '[]')
                        dayListDirect = JSON.stringify('[]')
                    }
                }

            })
        }

        {#getCalendarList(yearSelect)#}

        var vdata = getVirtualData(yearSelect)

        function getVirtualData(year) {
            dayList = dayListDirect
            {#getCalendarList()#}
            console.log('dayList', dayList)
            {#console.log('dayList p.length', JSON.parse(dayList).length)#}
            {#getCalendarList()#}
            let dayListN = JSON.parse(dayList)
            {#let dayListN = []#}
            console.log('dayListN:', dayListN)
            if (dayListN == null) {
                dayListN = []
            }
            console.log('getVirtualData dayList', dayListN)
            const date = +echarts.time.parse(year + '-01-01');
            const end = +echarts.time.parse(+year + 1 + '-01-01');
            const dayTime = 3600 * 24 * 1000;
            const data = [];
            var cday = 0
            for (let time = date; time < end; time += dayTime) {//every day
                let showDate = echarts.time.format(time, '{yyyy}-{MM}-{dd}', false)//every day formatter
                let pushAlready = false;
                for (; cday < dayListN.length;) { //dayListN is ordered list maybe shorter than outter for loop dates
                    let day = (dayListN[cday].calendar_day)
                    if (day === showDate) {//if date equals then push to data and set pushAlready 2 true and increase cday++ (judgement next day) and
                        // then break this loop
                        {#console.log('day:' + day + ',showDate:' + showDate)#}
                        data.push([
                            showDate, 24
                        ]);
                        pushAlready = true
                        cday++
                        break;
                    } else {
                        break;
                        //else break this loop,(waiting for the next date from outter loop)

                    }
                }
                if (!pushAlready) {
                    data.push([
                        showDate
                        ,
                        0
                    ]);
                }

            }
            return data;
        }

        let graphData = [
            {#['2016-02-04', 200],#}
            {#['2016-02-09', 279],#}
        ];

        option = {
            {#color: ["#c0c1cc", "#c9bbcf", "#b8a8bd", "#aca7c8", "#a09ad1", "#d2b48c", "#373715", "#755dff", "#b78d82"],#}
            title: {
                top: 30,
                left: 'center',
                text: '工作日历'
            },
            aria: {
                // 下面几行可以不写，因为 label.enabled 默认 true
                // label: {
                //     enabled: true
                // },
                enabled: true,
                data: {
                    maxCount: 4,
                }
            },
            {% comment %} legend: {
                 top: '30',
                 left: '100',
                 data: ['dates', 'checkdates'],
                 textStyle: {
                     color: '#909'
                 }
             },{% endcomment %}
            tooltip: {
                show: true,
                {#formatter: '{b0}{c0}<br />'#}
                formatter: function (params, ticket, callback) {
                    let data0_date = JSON.parse(JSON.stringify(params.data))[0]
                    let data1_val = JSON.parse(JSON.stringify(params.data))[1]
                    let color = JSON.parse(JSON.stringify(params.color))
                    {#alert(color)#}
                    {#alert(value)#}
                    return '<div style="height:120px;width:220px;text-align: center">' +
                        '<label style="color:' + `${color}` + '">' + '*' + '</label> <br>' +
                        '时间:' + data0_date +
                        '<br>' +
                        '数据量:' + data1_val +
                        '</div>'
                }
            },
            visualMap: {
                min: 0,
                max: 24,
                type: 'piecewise',
                splitNumber: 2,
                orient: 'horizontal',
                left: 'center',
                top: 65,
                itemWidth: 25,
                itemHeight: 20,
                inRange: {
                    color: ['#b2d9f7', '#60b6f8', '#0d93f9', '#1864e7'],
                    symbolSize: [0, 100]
                },
                controller: {
                    inRange: {
                        symbolSize: [0, 100]
                    }
                },
                {#textStyle: #}
                {% comment %} formatter: function (value) {
                     return '>>> ' + value
                 },{% endcomment %}
                hoverLink: true,
            },
            calendar: {
                top: 120,
                left: 30,
                right: 30,
                cellSize: 20,
                range: yearSelect,
                itemStyle: {
                    borderType: 'dashed',
                    borderWidth: 1,
                },
                dayLabel: {
                    firstDay: 1,// 从周一开始
                    nameMap: 'ZH',
                    fontWeight: 'bold',
                    textShadowColor: '#123123',
                    textShadowBlur: 123,
                    textShadowOffsetY: 12,
                    textShadowOffsetX: 12,
                },
                monthLabel: {
                    nameMap: 'ZH',
                    formatter: '{yyyy}-{MM}'
                },
                yearLabel: {
                    position: 'bottom',
                    {#formatter: '{start}-{end}',#}
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        width: 5,
                        color: 'white',
                        type: 'solid'
                    }
                },

            },
            series: [
                {
                    name: 'checkdates',
                    type: 'graph',
                    emphasis: {
                        scale: true,
                        focus: 'self'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{b}: {@score}'
                        , distance: 2,
                        fontSize: 2
                    },
                    {#cursor: 'pointer',#}
                    edgeSymbol: ['circle', 'arrow'],
                    edgeLabel: {
                        show: true,
                        formatter: function (params) {
                            if (graphData.length == 2) {
                                return graphData[0][0] + '——>' + graphData[1][0];
                            } else if (graphData.length == 1) {
                                return ''
                            } else {
                                return ''
                            }
                        },
                        color: 'black',
                        textBorderColor: 'yellow',
                        borderWidth: 1,
                        borderRadius: 2,
                        borderType: 'dotted',
                        borderColor: 'red',
                        align: 'center',
                        verticalAlign: 'bottom',
                        lineHeight: 12,
                        backgroundColor: 'white'
                        {#formatter: '{b}: {@score}'#}
                    },
                    {% comment %}categories: {
                        symbol: 'roundRect'
                    },{% endcomment %}
                    autoCurveness: true,
                    coordinateSystem: 'calendar',
                    links: null,
                    symbolSize: 8,
                    edgeSymbolSize: 8,
                    calendarIndex: 0,
                    itemStyle: {
                        scale: false,
                        opacity: 0.2,
                        color: 'white',
                        shadowBlur: 1,
                        shadowOffsetX: 1,
                        shadowOffsetY: 1,
                        {#shadowColor: 'black',#}
                        {#borderCap: 'square',#}
                        {#borderJoin: 'miter',#}
                        {#borderMiterLimit: 2#}
                    },
                    lineStyle: {
                        color: 'red',
                        width: 1,
                        opacity: 0.85,
                        {#type: 'dashed',#}
                        {#cap: 'square',#}
                        {#join: 'miter',#}
                        {#miterLimt: 1,#}
                    },
                    data: null,
                    z: 24
                },
                {
                    name: 'dates',
                    type: 'heatmap',
                    coordinateSystem: 'calendar',
                    //get work calendar date from DB
                    data: getVirtualData(yearSelect),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 0.2,
                            shadowColor: 'rgba(1, 1, 0, 0.5)'
                        }
                    },
                    label: {
                        show: true,
                        formatter: function (params) {
                            var d = new Date(params.value[0]);
                            return d.getDate();
                        },
                        color: "#000"
                    },
                },
            ]
        };
        myChart.setOption(option);
        //click calendar element event
        myChart.on("click", function (params) {
            option.tooltip.show = false
            let seriesIndex = params.seriesIndex;
            let dataIndex = params.dataIndex;
            {% comment %}  myChart.dispatchAction({
                  type: "downplay" //取消高亮指定的数据图形。通过seriesName或者seriesIndex指定系列。如果要指定某个数据可以再指定dataIndex或者name。
              });{% endcomment %}
            {% comment %} myChart.dispatchEvent({
                 type: "highlight", //高亮指定的数据图形。通过seriesName或者seriesIndex指定系列。如果要再指定某个数据可以再指定dataIndex或者name。         //取消高亮指定的数据图形。通过seriesName或者seriesIndex指定系列。如果要指定某个数据可以再指定dataIndex或者name。
                 seriesIndex: seriesIndex, // 可选，系列 index，可以是一个数组指定多个系列
                 dataIndex: dataIndex // 可选，数据的 index
             });{% endcomment %}
            console.log('click calendar ', params);
            if (params.data && params.value) {
                console.log('click ')
                console.log('params.name ', params.name)
                console.log('params.value ', params.value)
                let calendarCell = params.value
                console.log('option:', option)
                graphData.push(calendarCell)
                console.log('graphData', graphData)
                if (graphData.length === 1) {
                    option.series[0].links = null
                    option.series[0].data = null
                    myChart.setOption(option)
                }
                if (graphData.length > 1) {
                    console.log('graphData[0]', graphData[0])
                    console.log('graphData[1]', graphData[1])
                    console.log('graphData[0][0]===graphData[1][0]', graphData[0][0] === graphData[1][0])
                    if (graphData[0][0] == graphData[1][0]) {
                        graphData.pop()
                        return;
                    }
                    graphData.sort()
                    let links = graphData.map(function (item, idx) {
                        return {
                            source: idx,
                            target: idx + 1,
                            value: 1,
                            {% comment %}  lineStyle: {
                                  cap: 'square'
                              }{% endcomment %}
                        };
                    });
                    links.pop();
                    option.series[0].links = links
                    option.series[0].data = graphData
                    myChart.setOption(option)
                    let confirm = layer.confirm('导出工作记录？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        // 导出excel
                        exportWorksByTimeRange(graphData)
                        {#graphData = []#}
                        layer.msg('正在导出')
                        layer.close(confirm)
                        graphData = []
                        option.series[0].links = null
                        option.series[0].data = []
                        myChart.setOption(option)
                    }, function () {
                        graphData = []
                        option.series[0].links = null
                        option.series[0].data = []
                        myChart.setOption(option)
                    });
                }
                console.log('params.value[0] ', params.value[0])
                {#console.log('params.seriesName ', params.seriesName)#}


                {#window.location.href = "/manage/" + pid + "/issues/?status=" + (yMatchTypes.indexOf(params.name) + 1) +#}
                {#    "&issues_type=" + (issues_types[(xMatchTypes.indexOf(params.seriesName))])#}
            }
        });

        function getCheckDate(params) {
            let that = this;
            that.chart.on("click", function (e) {
                alert(e.data[0])
            });
        }

        //导出工作列表
        function exportWorksByTimeRange(graphData) {
            window.location.href = "{% url 'calendar_time_range_export_works' project_id=request.web.project.id %}?begin_time=" + graphData[0][0]
                + '&end_time=' + graphData[1][0] + '&csrfmiddlewaretoken=' + $("#csrf_token").val()

        }

        //导出任务列表
        function exportTasksByTimeRange(graphData) {
            $.ajax({
                url: "{% url 'calendar_time_range_export_tasks' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "time_range": graphData,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.status) {
                        console.log("reload")
                        location.reload();
                    } else {

                    }
                }

            })
        }

        let thisCalEditDataId = null;
        myChart.on("dblclick", function (params) {
            if (params.data && params.value && params.value[0]) {
                option.series[0].links = null
                option.series[0].data = null
                myChart.setOption(option)
                layui.use(function () {
                    var util = layui.util;
                    var layer = layui.layer;
                    let prompt = layer.prompt({
                                id: 'work_content_area',
                                title: '请输入或更新' + params.value[0] + '工作记录',
                                formType: 2,
                                area: ['680px', '420px'],
                                closeBtn: 1,
                                maxlength: 5000,
                                shade: [0.3, '#FFF'],
                                shadeClose: true,
                                resize: true,
                                minStack: true,
                                btn2: function () {
                                    graphData = []
                                    option.series[0].links = null
                                    option.series[0].data = []
                                    myChart.setOption(option)
                                }
                            }
                            , function (value, index, elem) {
                                console.log('prompt elem :', elem)
                                console.log('prompt index :', index)
                                {#if (value === '') return elem.focus();#}
                                layer.msg('获得：' + util.escape(value)); // 显示 value
                                //send calendayDayContent to save
                                if (thisCalEditDataId && document.querySelector(".layui-layer-input").value.length > 0) {
                                    //更新记录
                                    updateCalendarContent(thisCalEditDataId, document.querySelector(".layui-layer-input").value)
                                } else if (!thisCalEditDataId && document.querySelector(".layui-layer-input").value.length > 0) {
                                    //新增记录
                                    sendCalendarDayContent(params.value[0], util.escape(value));
                                } else if (thisCalEditDataId && document.querySelector(".layui-layer-input").value.length == 0) {
                                    //删除该条记录
                                    delCalendarRecord(thisCalEditDataId, document.querySelector(".layui-layer-input").value)
                                }
                                getCalendarList(yearSelect)
                                vdata = getVirtualData(yearSelect)
                                setTimeout(function () {
                                    // 关闭 prompt
                                    layer.close(index);
                                    {#window.location.reload()#}
                                }, 1500);
                            }
                        )
                    ;
                    layer.style(prompt, {
                        width: '800px',
                        height: '600px',
                        top: '10px',
                    });

                    let textArea = document.querySelector(".layui-layer-input")
                    let bottomBtnArr = document.querySelector(".layui-layer-btn")
                    let spanMaxLength = document.createElement('span');
                    spanMaxLength.id = 'maxlengthlabel'
                    spanMaxLength.style = 'float:left'
                    //getCalendarDayContentByCalendarDay and current user and current proejct
                    $.ajax({
                        url: "{% url 'find_work_record' project_id=request.web.project.id %}",
                        type: "GET",
                        data: {
                            "calendar_day": params.value[0],
                            "csrfmiddlewaretoken": $("#csrf_token").val()
                        },
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                {#alert(JSON.stringify(res.record.content))#}
                                textArea.value = eval(JSON.stringify(res.record.content))
                                thisCalEditDataId = eval(JSON.stringify(res.record.id))
                                spanMaxLength.innerHTML = '字数限制 ' + textArea.value.length + "/5000";
                                bottomBtnArr.appendChild(spanMaxLength)
                                {#$(".layui-layer-input").html(JSON.stringify(res.record.content))#}
                                //res.record.id  (to update calendar record)
                                //res.record.create_time
                                //res.record.update_time
                            } else {
                                console.log("can not get record")
                                thisCalEditDataId = null;
                            }
                        },
                        error: (err) => {
                            layer.msg(err)
                            thisCalEditDataId = null;
                        }

                    })
                    //when press esc (event27) then close prompt of editor
                    $(document).keyup(function (event) {
                        if (event.which === 27) {
                            //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算
                            layer.close(prompt);
                        }
                    })
                    spanMaxLength.innerHTML = '字数限制 ' + textArea.value.length + "/5000";
                    bottomBtnArr.appendChild(spanMaxLength)
                    textArea.addEventListener('input', () => {
                        document.getElementById("maxlengthlabel").innerHTML = '字数限制 ' + textArea.value.length + "/5000";
                        bottomBtnArr.appendChild(spanMaxLength)
                    })
                })
            }
        })

        function sendCalendarDayContent(day, content) {
            if (!day || !content) {
                return
            }
            $.ajax({
                url: "{% url 'add_work_record' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "content": content,
                    "calendar_day": day,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.status) {
                        window.location.reload()
                        layer.msg('保存成功')
                    } else {
                        layer.msg('保存失败')
                    }
                }
            })
        }

        function updateCalendarContent(id, content) {
            if (!id || !content) {
                return
            }
            $.ajax({
                url: "{% url 'work_record_update' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "id": id,
                    "content": content,
                    //nginx 真的好学吗
                    // nginx有几个模块
                    // 1-二进制可执行文件，
                    // 2-conf配置文件，
                    // 3-access.log访问日志，
                    // 4-error.log异常日志
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.status) {
                        window.location.reload()
                        layer.msg('更新成功')
                    } else {
                        layer.msg('更新失败')
                    }
                    {#option.calendar.range = yearSelect#}
                    {#option.series[1].data = getVirtualData(yearSelect)#}
                    {#myChart.setOption(option)#}
                }
            })
        }

        function delCalendarRecord(id, content) {
            if (!id || content) {
                return
            }
            $.ajax({
                url: "{% url 'work_record_update' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "id": id,
                    "content": content,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.status) {
                        window.location.reload()
                        layer.msg('删除成功')
                    } else {
                        layer.msg('删除失败')
                    }
                }
            })
        }

        function getCalendarDayContent(day) {
            $.ajax({
                url: "{% url 'find_work_record' project_id=request.web.project.id %}",
                type: "GET",
                data: {
                    "calendar_day": day,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                {#dataType: "JSON",#}
                success: function (res) {
                    console.log(res);
                    if (res.status) {
                        console.log("record ", res.record)
                        location.reload();
                        layer.msg('查询成功')
                    } else {

                    }
                }

            })
        }

        layui.use(function () {
            console.log('layui use function ');
            var laydate = layui.laydate;
            getCalendarList(yearSelect)
            vdata = getVirtualData(yearSelect)
            option.calendar.range = yearSelect
            option.series[1].data = getVirtualData(yearSelect)
            myChart.setOption(option)
            // 年选择器
            laydate.render({
                elem: '#ID-laydate-type-year',
                value: yearSelect,
                type: 'year',
                done: function (value, date, endDate) {
                    console.log(date.year);
                    yearSelect = date.year
                    localStorage.setItem("yearSelect", yearSelect)
                    getCalendarList(yearSelect)
                    vdata = getVirtualData(yearSelect)
                    option.calendar.range = date.year
                    option.series[1].data = getVirtualData(date.year)
                    myChart.setOption(option)
                    {#$("#body-content").load(location.href + "#body-content")#}
                    {#console.log(value); // 日期字符，如： 2017-08-18#}
                    {#console.log(date); // 包含年月日时分秒各项值的对象#}
                    {#console.log(endDate); // 结束日期时间对象，当设置 range 时才会返回。对象成员同上。#}
                }
            });
        });
    </script>
{% endblock %}